package cn.xfdzx.android.apps.shop.video;


import android.app.Dialog;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.luck.picture.lib.tools.StringUtils;
import com.luck.picture.lib.tools.ToastUtils;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLivePlayConfig;
import com.tencent.rtmp.TXLivePlayer;
import com.tencent.rtmp.TXLog;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.tencent.ugc.TXRecordCommon;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.InputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.activity.GoodCarActivity;
import cn.xfdzx.android.apps.shop.activity.GoodsDetailsActivity;
import cn.xfdzx.android.apps.shop.activity.PaySuccessfulNewActivity;
import cn.xfdzx.android.apps.shop.activity.ShopActivity;
import cn.xfdzx.android.apps.shop.activity.XFDGoodsDeatailsActivity;
import cn.xfdzx.android.apps.shop.activity.XFDShopDetailsActivity;
import cn.xfdzx.android.apps.shop.activity.login.OneLoginMainActivity;
import cn.xfdzx.android.apps.shop.activity.myshop.CreatePusherActivity;
import cn.xfdzx.android.apps.shop.adapter.VideoGoodListAdapter;
import cn.xfdzx.android.apps.shop.adapter.VideoHeadListAdapter;
import cn.xfdzx.android.apps.shop.adapter.VideoUserGoodListAdapter;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.ConfirmGoodBeen;
import cn.xfdzx.android.apps.shop.bean.CustomerMsgBeen;
import cn.xfdzx.android.apps.shop.bean.LogininfoBean;
import cn.xfdzx.android.apps.shop.bean.PusherEventBean;
import cn.xfdzx.android.apps.shop.bean.ShopTimeBean;
import cn.xfdzx.android.apps.shop.bean.VideoAvatarListBeen;
import cn.xfdzx.android.apps.shop.bean.VideoInfoBeen;
import cn.xfdzx.android.apps.shop.bean.VideoRoomGoodListBeen;
import cn.xfdzx.android.apps.shop.contract.ItemClickListener;
import cn.xfdzx.android.apps.shop.contract.VideoInfoContract;
import cn.xfdzx.android.apps.shop.demo.common.TCLiveRoomMgr;
import cn.xfdzx.android.apps.shop.demo.common.activity.ErrorDialogFragment;
import cn.xfdzx.android.apps.shop.demo.common.utils.TCConstants;
import cn.xfdzx.android.apps.shop.demo.common.utils.TCFrequeControl;
import cn.xfdzx.android.apps.shop.demo.common.widget.TCInputTextMsgDialog;
import cn.xfdzx.android.apps.shop.demo.common.widget.TCSwipeAnimationController;
import cn.xfdzx.android.apps.shop.demo.common.widget.TCVideoWidget;
import cn.xfdzx.android.apps.shop.demo.common.widget.TCVideoWidgetList;
import cn.xfdzx.android.apps.shop.demo.common.widget.danmaku.TCDanmuMgr;
import cn.xfdzx.android.apps.shop.demo.common.widget.like.TCHeartLayout;
import cn.xfdzx.android.apps.shop.demo.liveroom.ILiveRoomListener;
import cn.xfdzx.android.apps.shop.demo.liveroom.LiveRoom;
import cn.xfdzx.android.apps.shop.demo.liveroom.roomutil.commondef.PusherInfo;
import cn.xfdzx.android.apps.shop.demo.liveroom.roomutil.commondef.RoomInfo;
import cn.xfdzx.android.apps.shop.demo.liveroom.roomutil.im.TCChatEntity;
import cn.xfdzx.android.apps.shop.demo.liveroom.roomutil.im.TCChatMsgListAdapter;
import cn.xfdzx.android.apps.shop.demo.liveroom.roomutil.im.TCSimpleUserInfo;
import cn.xfdzx.android.apps.shop.demo.liveroom.roomutil.login.JoinRoomSuccessEvent;
import cn.xfdzx.android.apps.shop.demo.liveroom.roomutil.login.TCUserMgr;
import cn.xfdzx.android.apps.shop.evenbus.BuyLiveGoodsMessage;
import cn.xfdzx.android.apps.shop.evenbus.IMloginMessage;
import cn.xfdzx.android.apps.shop.evenbus.VideoListMessage;
import cn.xfdzx.android.apps.shop.presenter.VideoInfoPresenter;
import cn.xfdzx.android.apps.shop.util.EmptyUtil;
import cn.xfdzx.android.apps.shop.util.ImageGlideUtil;
import cn.xfdzx.android.apps.shop.util.KeybordUtil;
import cn.xfdzx.android.apps.shop.util.SendValidateTimerUtil;
import cn.xfdzx.android.apps.shop.util.ShopCarPopupWindow;
import cn.xfdzx.android.apps.shop.util.StatusBarUtil;
import cn.xfdzx.android.apps.shop.util.StreamUtil;

import cn.xfdzx.android.apps.shop.util.Utils;
import cn.xfdzx.android.apps.shop.util.UtilsData;
import cn.xfdzx.android.apps.shop.widget.ChooseShareTypeDialog;
import cn.xfdzx.android.apps.shop.widget.CustomerPopwindow;
import cn.xfdzx.android.apps.shop.widget.SelShopTimePopwindow;
import cn.xfdzx.android.apps.shop.widget.ShowLiveOnLiveCountDialog;

import static cn.xfdzx.android.apps.shop.apps.Constants.APP_TOKEN;

/**
 * 直播拉流页面
 **/
public class VideoActivity extends BaseMvpActivity<VideoInfoPresenter> implements VideoInfoContract.View, View.OnClickListener, ILiveRoomListener{


    private static final int CACHE_STRATEGY_FAST = 1;  //极速
    private static final int CACHE_STRATEGY_SMOOTH = 2;  //流畅
    private static final int CACHE_STRATEGY_AUTO = 3;  //自动

    private RelativeLayout img_close;
    /**
     * SDK player 相关
     */
    private TXLivePlayer mLivePlayer = null;
    private TXLivePlayConfig mPlayConfig;
    private TXCloudVideoView mPlayerView;
    private String liveId;//直播间id

    private int mCurrentRenderRotation;
    private static final String TAG = VideoActivity.class.getSimpleName();
    /**
     * IM聊天室相关
     */
    private TextView btn_message_input;//消息输入框
    private TCInputTextMsgDialog mInputTextMsgDialog;
    private ListView mListViewMsg;
    private ArrayList<TCChatEntity> mArrayListChatEntity = new ArrayList<>();
    private TCChatMsgListAdapter mChatMsgListAdapter;
    private List<PusherInfo> mPusherList = new ArrayList<>();
    private TCVideoWidgetList mPlayerList;
    protected LiveRoom mLiveRoom;
    private long mCurrentMemberCount = 0;
    private long mTotalMemberCount = 0;
    private long mHeartCount = 0;
    protected boolean mPausing = false;
    private boolean mPlaying = false;
    private String mGroupId = "";
    private String mFileId = "";
    protected String mUserId = "";
    protected String mNickname = "";
    protected String mHeadPic = "";
    private String shopID = "";

    //点赞动画
    private TCHeartLayout mHeartLayout;
    //点赞频率控制
    private TCFrequeControl mLikeFrequeControl;

    //弹幕
    private TCDanmuMgr mDanmuMgr;

    //手势动画
    private RelativeLayout mControllLayer;
    private TCSwipeAnimationController mTCSwipeAnimationController;
    protected ImageView mBgImageView;
    private ErrorDialogFragment mErrDlgFragment = new ErrorDialogFragment();
    private RelativeLayout rl_play_root;
    private long mStartPushPts;

    protected Handler mHandler = new Handler();
    private ImageView img_headview;//主播头像
    private TextView tv_shopname;//店铺名称
    private TextView tv_focus;//关注
    private TextView tv_fensnum;//粉丝数
    private TextView tv_roomid;//房间id显示
    private ImageView btn_goods;//购物袋
    private ImageView btn_share;//分享
    private ImageView btn_zan;//点赞
    private RelativeLayout rlPopupRoot;//  商品PW
    private RelativeLayout rlPopupRootTitle;//  商品PW标题头
    private RelativeLayout rlShopInfo;//  商家信息
    private RecyclerView rvList;//商品列表 购物车
    private VideoUserGoodListAdapter videoGoodListAdapter;
    private RecyclerView rv_user_topavatar;//用户头像列表
    private VideoHeadListAdapter videoTopHeadListAdapter;//用户头像列表适配器
    //直播间 的商品
    private List<VideoRoomGoodListBeen.DataBean.GoodsBean> goodList = new ArrayList<>();
    private TextView tvTotalNum;

    //直播结束布局
    private RelativeLayout rl_end_video;//直播结束布局显示
    private ImageView ivLogo;//直播间图片
    private TextView tv_shop_name;//直播间结束显示的店铺名称
    private TextView tv_finish;//结束返回按钮
    private int joinCount = 0;
    private TextView tvCarNum;
    private View viewGoodCarBg;//商品列表的背景
    private ImageView ivCarListBack;//商品列表的回退
    private int shop_type = 0;//是零售的还是批发的
    private ImageView ivGoodCar;
    private int isFocus;//是否关注主播，取消关注时弹窗
    private int follow_num;//粉丝数量
    private int msgType;//消息类型
    private String msgContext;//名称
    private List<CustomerMsgBeen> msgBeenList = new ArrayList<>();
    private Animation transtoLeftAnim;
    private Animation transtoRightAnim;
    private TextView tv_pop;//pop动画
    private LinearLayout ll_pop;
    private LinearLayout ll_input;//输入框布局
    private InputMethodManager inputMethodManager;
    private EditText et_input_message;
    private TextView confrim_btn;//发送按钮
    private boolean isFirst = true;
    private TextView tv_zancount;//点赞数
    private int zan_num = 0;
    private MyHandler myHandler = new MyHandler(this);
    private MyHandler myHandlerReconnection;
    private List<VideoAvatarListBeen> videoTopAvatarList = new ArrayList<>();//直播间顶部用户头像列表
    private List<VideoAvatarListBeen> videoMoreAvatarList = new ArrayList<>();//直播间顶部用户头像列表
    private List<VideoInfoBeen.DataBean.StoreInfoBean.ViewersBean> viewers = new ArrayList<>();//直播间头像列表
    private TextView tv_lookmore;//更多头像
    private LinearLayout ll_addheadlist;//顶部头像动态列表添加布局
    private View itemHeadView;//头像布局
    private TextView tv_video_end;//直播结束不久展示的信息（已结束，已离开）
    @Override
    public int getLayoutId() {
        return R.layout.activity_video;
    }

    @Override
    public void initView() {
        liveId = getIntent().getStringExtra("live_id");
        //mGroupId = getIntent().getStringExtra("chat_id");
        shop_type = getIntent().getIntExtra("shop_type", 0);
        EventBus.getDefault().register(this);
        initOnPreDrawListener();
        mLiveRoom = TCLiveRoomMgr.getLiveRoom(this);
        mLiveRoom.updateSelfUserInfo(mNickname, mHeadPic);

        mPresenter = new VideoInfoPresenter();
        mPresenter.attachView(this);
        mPresenter.videoInfo(liveId);
        btn_message_input = findViewById(R.id.btn_message_input);
        img_close = findViewById(R.id.img_close);
        img_headview = findViewById(R.id.img_headview);
        tv_shopname = findViewById(R.id.tv_shopname);
        tv_focus = findViewById(R.id.tv_focus);
        tv_fensnum = findViewById(R.id.tv_shopfens);
        tv_roomid = findViewById(R.id.tv_pusherid);
        btn_goods = findViewById(R.id.btn_goods);
        btn_share = findViewById(R.id.btn_share);
        btn_zan = findViewById(R.id.btn_zan);
        rl_play_root = findViewById(R.id.rl_play_root);
        rl_end_video = findViewById(R.id.rl_end_video);
        tv_video_end = findViewById(R.id.tv_video_end);
        tv_shop_name = findViewById(R.id.tv_shop_name);
        ivLogo = findViewById(R.id.iv_logo);
        tv_finish = findViewById(R.id.tv_finish);
        tvCarNum = findViewById(R.id.tv_car_num);
        ivGoodCar = findViewById(R.id.iv_good_car);
        tvTotalNum = findViewById(R.id.tv_total_num);
        rlPopupRoot = findViewById(R.id.rl_popup_root);
        rlPopupRootTitle = findViewById(R.id.rl_popup_root_title);
        rlShopInfo = findViewById(R.id.rl_shop_info);
        rvList = findViewById(R.id.rv_good_list);
        viewGoodCarBg = findViewById(R.id.view_good_car_bg);
        ivCarListBack = findViewById(R.id.iv_car_list_back);
        tv_pop = findViewById(R.id.tv_pop);
        ll_pop = findViewById(R.id.ll_pop);
        ll_input = findViewById(R.id.ll_input);
        rv_user_topavatar = findViewById(R.id.rv_user_avatar);
        et_input_message = findViewById(R.id.et_input_message);
        confrim_btn = findViewById(R.id.confrim_btn);
        tv_zancount = findViewById(R.id.tv_zancount);
        tv_lookmore = findViewById(R.id.tv_lookmore);
        ll_addheadlist = findViewById(R.id.ll_addheadlist);
        mCurrentRenderRotation = TXLiveConstants.RENDER_ROTATION_PORTRAIT;
//mPlayerView 即 step1 中添加的界面 view
        mPlayerView = findViewById(R.id.video_view);
//创建 player 对象
        mLivePlayer = new TXLivePlayer(this);
//关键 player 对象与界面 view
        mLivePlayer.setPlayerView(mPlayerView);
// 设置填充模式
        mLivePlayer.setRenderMode(TXLiveConstants.RENDER_MODE_FULL_FILL_SCREEN);
        // mLivePlayer.setRenderMode(TXLiveConstants.RENDER_MODE_ADJUST_RESOLUTION);
// 设置画面渲染方向
        mLivePlayer.setRenderRotation(TXLiveConstants.RENDER_ROTATION_PORTRAIT);
        mPlayerList = new TCVideoWidgetList(this, null);
        mInputTextMsgDialog = new TCInputTextMsgDialog(this, R.style.InputDialog);

        mControllLayer = (RelativeLayout) findViewById(R.id.rl_controllLayer);
        mTCSwipeAnimationController = new TCSwipeAnimationController(this);
        mTCSwipeAnimationController.setAnimationView(mControllLayer);
        mListViewMsg = (ListView) findViewById(R.id.im_msg_listview);
        mListViewMsg.setVisibility(View.VISIBLE);
        mHeartLayout = (TCHeartLayout) findViewById(R.id.heart_layout);
        mChatMsgListAdapter = new TCChatMsgListAdapter(this, mListViewMsg, mArrayListChatEntity);
        mListViewMsg.setAdapter(mChatMsgListAdapter);

        mCurrentMemberCount++;
        rl_play_root.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return mTCSwipeAnimationController.processEvent(event);
            }
        });
        //在这里停留，让列表界面卡住几百毫秒，给sdk一点预加载的时间，形成秒开的视觉效果
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

//        tvStart.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (mCurrentRenderRotation == TXLiveConstants.RENDER_ROTATION_PORTRAIT) {
//                    tvStart.setText("竖屏");
//                    mCurrentRenderRotation = TXLiveConstants.RENDER_ROTATION_LANDSCAPE;
//                } else if (mCurrentRenderRotation == TXLiveConstants.RENDER_ROTATION_LANDSCAPE) {
//                    tvStart.setText("横屏");
//                    mCurrentRenderRotation = TXLiveConstants.RENDER_ROTATION_PORTRAIT;
//                }
//                mLivePlayer.setRenderRotation(mCurrentRenderRotation);
//            }
//        });

        btn_message_input.setOnClickListener(this);
        img_close.setOnClickListener(this);
        tv_focus.setOnClickListener(this);
        btn_goods.setOnClickListener(this);
        btn_share.setOnClickListener(this);
        btn_zan.setOnClickListener(this);
        tv_finish.setOnClickListener(this);
        rlShopInfo.setOnClickListener(this);
        confrim_btn.setOnClickListener(this);
        rv_user_topavatar.setOnClickListener(this);
        tv_lookmore.setOnClickListener(this);
        ll_addheadlist.setOnClickListener(this);
        initCar();
        initDialog();//取消关注弹窗
        initAnimationListener();//初始化动画监听
        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(et_input_message, InputMethodManager.SHOW_FORCED);
        initSofrInputListener();
      //  initUserAvatarrRecycle();
    }

    /**
     * 初始化头像列表适配器
     * */
    private void initUserAvatarrRecycle() {
//        videoAvatarList.add(new VideoAvatarListBeen("","1"));
//        videoAvatarList.add(new VideoAvatarListBeen("","2"));
//        videoAvatarList.add(new VideoAvatarListBeen("","3"));
        videoTopHeadListAdapter = new VideoHeadListAdapter(this,videoTopAvatarList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_user_topavatar.setLayoutManager(linearLayoutManager);
        rv_user_topavatar.setAdapter(videoTopHeadListAdapter);

        videoTopHeadListAdapter.setItemOnClickListener(new VideoHeadListAdapter.OnItemOnClickListener() {
            @Override
            public void onItemClick() {
                showLiveOnLiveCountDialog();
            }
        });
    }

    private int mLastDiff = 0;
    /**
     * 设置输入框监听
     * */
    public void initSofrInputListener(){
        et_input_message.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                switch (actionId) {
                    case KeyEvent.KEYCODE_ENDCALL:
                    case KeyEvent.KEYCODE_ENTER:
                        Log.e("et_input_message",et_input_message.getText().length()+"----");
                        if (et_input_message.getText().length() > 0) {

//                            mOnTextSendListener.onTextSend("" + messageTextView.getText(), mDanmuOpen);
                            //sendText("" + messageTextView.getText());
                            //imm.showSoftInput(messageTextView, InputMethodManager.SHOW_FORCED);
                            inputMethodManager.hideSoftInputFromWindow(et_input_message.getWindowToken(), 0);
//                            messageTextView.setText("");
                            ll_input.setVisibility(View.GONE);
                            mLastDiff = 0;
                        } else {
                            Toast.makeText(VideoActivity.this, "输入内容不能为空!", Toast.LENGTH_LONG).show();
                        }
                        return true;
                    case KeyEvent.KEYCODE_BACK:
                        ll_input.setVisibility(View.GONE);
                        mLastDiff = 0;
                        return false;
                    default:
                        return false;
                }
            }
        });

        ll_pop.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View view, int i, int i1, int i2, int i3, int i4, int i5, int i6, int i7) {
                Rect r = new Rect();
                //获取当前界面可视部分
                getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                //获取屏幕的高度
                int screenHeight =  getWindow().getDecorView().getRootView().getHeight();
                //此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
                int heightDifference = screenHeight - r.bottom;

                Log.e("ll_input",heightDifference+"-----");
                if (heightDifference <= 0 && mLastDiff > 0){
                    //imm.hideSoftInputFromWindow(messageTextView.getWindowToken(), 0);
                   // dismiss();
                    ll_input.setVisibility(View.GONE);
                }

//                if (heightDifference>0){
//                    ll_input.setVisibility(View.VISIBLE);
//                }
                if (heightDifference>100&&heightDifference<200){
                    ll_input.setVisibility(View.GONE);
                    Log.e("ll_input",heightDifference+"->100-<200-");
                }
                 if (heightDifference>200){
                    ll_input.setVisibility(View.VISIBLE);
                     Log.e("ll_input",heightDifference+"-->200--");
                }
                mLastDiff = heightDifference;
            }
        });

    }
    private void initCar() {
        //购物袋里的商品adapter
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvList.setLayoutManager(linearLayoutManager);
        videoGoodListAdapter = new VideoUserGoodListAdapter(this, goodList, mPresenter);
        videoGoodListAdapter.setOnItemClickListener(new ItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (Utils.isFastClick()) {
                    if (!shopID.isEmpty()) {
                        if (shop_type==0) {
                            Intent intent = new Intent(VideoActivity.this, GoodsDetailsActivity.class);
                            intent.putExtra("good_id", goodList.get(position).getId() + "");

                            startActivity(intent);
                        }else {
                            Intent intent = new Intent(VideoActivity.this, XFDGoodsDeatailsActivity.class);
                            intent.putExtra("good_id", goodList.get(position).getId() + "");
                            startActivity(intent);
                        }
                    }
                }

            }
        });
        /**
         * 添加购物车回调，通知其他用户添加了几号商品到购物车
         * */
        videoGoodListAdapter.setAddCartClickkListener(new VideoUserGoodListAdapter.OnAddCartClickListener() {
            @Override
            public void onAddCartClick(int position) {
                //发送添加到购物车消息
                mLiveRoom.sendRoomCustomMsg(String.valueOf(TCConstants.IMCMD_ADDCART), position+1+"", (LiveRoom.SendCustomMessageCallback) null);
            }
        });

        rvList.setAdapter(videoGoodListAdapter);
        if (shop_type == 0) {
            tvCarNum.setText(UtilsData.getPreference(this, "carCount").getInteger("car_ls_count") + "");
        } else {
            tvCarNum.setText(UtilsData.getPreference(this, "carCount").getInteger("car_pf_count") + "");
        }
        ivGoodCar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    //购物车 跳转
                    Intent intent = new Intent(VideoActivity.this, GoodCarActivity.class);
                    intent.putExtra("type", shop_type);
                    startActivity(intent);
                }
            }
        });
    }

    /**
     * 显示房间信息
     */
    private void showRoomInfo(VideoInfoBeen bean) {
        tv_roomid.setText("ID:" + liveId);
        //针对零售和批发商户，先判断getOffline_shop_name是否为空，没有则取getName
        if (shop_type == 1) {
            if (EmptyUtil.isNotEmpty(bean.getData().getStoreInfo().getName())) {
                tv_shopname.setText(bean.getData().getStoreInfo().getName());
                tv_shop_name.setText(bean.getData().getStoreInfo().getName());
            }
        } else {
            tv_shopname.setText(bean.getData().getStoreInfo().getOffline_shop_name());
            tv_shop_name.setText(bean.getData().getStoreInfo().getOffline_shop_name());
        }
        RoundedCorners roundedCorners = new RoundedCorners(20);
        //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
        RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).override(200, 200);
        options.placeholder(R.drawable.icon_defult)//图片加载出来前，显示的图片
                .fallback(R.drawable.icon_defult) //url为空的时候,显示的图片
                .error(R.drawable.icon_defult);
        Glide.with(this).load(bean.getData().getStoreInfo().getLogo()).apply(options.transform(new CircleCrop(), roundedCorners)).into(ivLogo);

        tv_fensnum.setText("粉丝:" + bean.getData().getStoreInfo().getFollow_num());
        ImageGlideUtil.loadAvatar(this, img_headview, bean.getData().getStoreInfo().getLogo());
        if (bean.getData().getStoreInfo().getIs_follow() == 0) { //是否收藏 0否 1是
            tv_focus.setText("关注");
            isFocus = 0;
            setDrawableResource(getResources().getDrawable(R.drawable.ic_livefocus));
        }else {
            tv_focus.setText("已关注");
            isFocus = 1;
            setDrawableResource(null);
        }
        shopID = bean.getData().getStoreInfo().getId() + "";
        follow_num = bean.getData().getStoreInfo().getFollow_num();
        tv_fensnum.setText("粉丝: "+Utils.toNumber(follow_num));
        try {
            zan_num = Integer.parseInt(bean.getData().getStoreInfo().getFabulous_num());
        }catch (Exception e){
            zan_num = 0;
        }

        tv_zancount.setText(Utils.toNumber(zan_num));
        viewers = bean.getData().getStoreInfo().getViewers();

        if (viewers.size()>4){
            for (int i = 0; i < 4; i++) {
                videoTopAvatarList.add(new VideoAvatarListBeen(viewers.get(i).getUser().getAvatar(),
                        viewers.get(i).getUser().getNickname(), viewers.get(i).getUser().getId()+""));
            }

        }else {
            for (int i = 0; i < viewers.size(); i++) {
                videoTopAvatarList.add(new VideoAvatarListBeen(viewers.get(i).getUser().getAvatar(),
                        viewers.get(i).getUser().getNickname(),viewers.get(i).getUser().getId()+""));
            }
        }
        for (int i = 0; i < viewers.size(); i++) {
            videoMoreAvatarList.add(new VideoAvatarListBeen(viewers.get(i).getUser().getAvatar(),
                    viewers.get(i).getUser().getNickname(),viewers.get(i).getUser().getId()+""));
        }
        addTopHeadView();//动态添加头部头像方法
        //videoTopHeadListAdapter.refreshDatas(videoTopAvatarList);
        Log.e("tv_zancount",zan_num+"----");
//        if (follow_num>10000){
//            tv_fensnum.setText("粉丝: "+follow_num/10000+"w");
//        }else {
//            tv_fensnum.setText("粉丝: "+follow_num);
//        }

    }

    /**动态添加头像子view*/
    private void addTopHeadView() {
        ll_addheadlist.removeAllViews();
        for (int i = 0; i < videoTopAvatarList.size(); i++) {
            itemHeadView =  View.inflate(this, R.layout.item_livehead, null);
            ImageView itemImage = itemHeadView.findViewById(R.id.img_head);
            ImageGlideUtil.loadAvatar(this,itemImage,videoTopAvatarList.get(i).getHeadUrl());
            ll_addheadlist.addView(itemHeadView);
        }
       // itemHeadView =  View.inflate(this, R.layout.item_livehead, null);
    }

    /**设置开关图标*/
    private void setDrawableResource(Drawable drawable) {
        if (null == drawable){
            tv_focus.setCompoundDrawables(null, null, null, null);
        }else {
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tv_focus.setCompoundDrawables(drawable, null, null, null);
        }

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void onError(Throwable throwable) {

    }


    //收到用户购买消息通知
    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onBuyMessage(BuyLiveGoodsMessage messageEvent) {
        Log.e("LogininfoBean", messageEvent.getBuyMessage() + "--onBuyMessage--");
        PusherEventBean pusherEventBean = new Gson().fromJson(messageEvent.getBuyMessage(), PusherEventBean.class);
        if (pusherEventBean.getStatus()==1){//用户购买
            msgBeenList.add(new CustomerMsgBeen(TCConstants.IMCMD_BUY,pusherEventBean.getMsg()));
        }else if (pusherEventBean.getStatus()==2){//主播异常断流
            stopPlay(true);
            if (EmptyUtil.isNotEmpty(showLiveOnLiveCountDialog)){
                showLiveOnLiveCountDialog.dismiss();
            }
            rl_end_video.setVisibility(View.VISIBLE);//展示结束布局
            EventBus.getDefault().post(new VideoListMessage(0));
            tv_video_end.setText(pusherEventBean.getMsg());
        }

    }

    //用户登录成功之后网络请求IM登录
    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onImLogin(IMloginMessage messageEvent) {
        Log.e("LogininfoBean", messageEvent.getMessage() + "--onVideoLogin--");
        mPresenter.getLiveImLogin(liveId, "1");
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMainEvent(JoinRoomSuccessEvent event) {
        Log.e("startPlay", "JoinRoomSuccessEvent");
        // if (mPlaying) return;
        enterIMRoom();
    }

    @Override
    protected void onStart() {
        super.onStart();
        //防止购物车里  删除品类，数量更新
        if (shop_type == 0) {
            tvCarNum.setText(UtilsData.getPreference(this, "carCount").getInteger("car_ls_count") + "");
        } else {
            tvCarNum.setText(UtilsData.getPreference(this, "carCount").getInteger("car_pf_count") + "");
        }
    }

    @Override
    public void onVideoInfoSuccess(VideoInfoBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            mLivePlayer.startPlay(bean.getData().getPlay_url().getFlv(), TXLivePlayer.PLAY_TYPE_LIVE_FLV); //推荐 FLV
            mPlaying = true;
            showRoomInfo(bean);
            mPresenter.getLiveImLogin(liveId, "1");//请求获取用户IM账号和sign
            mGroupId = bean.getData().getStoreInfo().getChat_id();
            TCUserMgr.getInstance().initContext(this);
            if (EmptyUtil.isNotEmpty(APP_TOKEN)) {//如果用户登录了调用IM自动登录
                TCUserMgr.getInstance().autoLogin(null);
            }
            mUserId = UtilsData.getPreference(this, "IMlogin").getString("IMAccount");
            if (EmptyUtil.isNotEmpty(UtilsData.getPreference(this, "login").getString("nickname"))) {
                mNickname = mUserId;
            } else {
                mNickname = UtilsData.getPreference(this, "login").getString("nickname");
            }

            mHeadPic = UtilsData.getPreference(this, "login").getString("head_url") == null ? "" : UtilsData.getPreference(this, "login").getString("head_url");

            if (TextUtils.isEmpty(mNickname)) {
                mNickname = mUserId;
            }

            //保存IM群组id
            UtilsData.getPreference(VideoActivity.this, "IMlogin").put("chat_id", mGroupId);
            startTickWork();
        } else {
            if (bean.getStatus() == Constants.LOGIN_CODE) {
                UtilsData.getPreference(this, "login").remove("head_url");
                UtilsData.getPreference(this, "login").remove("nickname");
                UtilsData.getPreference(this, "login").remove("is_store");
                UtilsData.getPreference(this, "login").remove("token");
                APP_TOKEN = "";
                Intent intent = new Intent(this, OneLoginMainActivity.class);
                startActivity(intent);
                return;
            }
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getLiveImLoginSuccess(LogininfoBean bean) {
        if (bean.getStatus()== Constants.SUCCESS_CODE){
            //保存用户IM的uid 和sign
            UtilsData.getPreference(VideoActivity.this,"IMlogin").put("IMAccount",bean.getData().getUid());
            UtilsData.getPreference(VideoActivity.this,"IMlogin").put("IMSign",bean.getData().getUsersig());
          //  enterIMRoom();//加入IM群组

        } else {
            if (bean.getStatus() == Constants.LOGIN_CODE) {
                UtilsData.getPreference(this, "login").remove("head_url");
                UtilsData.getPreference(this, "login").remove("nickname");
                UtilsData.getPreference(this, "login").remove("is_store");
                UtilsData.getPreference(this, "login").remove("token");
                APP_TOKEN = "";
                Intent intent = new Intent(this, OneLoginMainActivity.class);
                startActivity(intent);
                return;
            }
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onVideoRoomGoodListSuccess(VideoRoomGoodListBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            goodList.clear();
            goodList.addAll(bean.getData().getGoods());
            videoGoodListAdapter.notifyDataSetChanged();
            tvTotalNum.setText("共" + goodList.size() + "件商品");
            if (viewGoodCarBg.getVisibility() == View.GONE) {
                startTranslationAnimation();
            }
            rlPopupRootTitle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //这里为了防止点标题隐藏
                }
            });
            viewGoodCarBg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    关闭平移动画
                    if (Utils.isFastClick()) {
                        endTranslationAnimation();
                    }
                }
            }); ivCarListBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    关闭平移动画
                    if (Utils.isFastClick()) {
                        endTranslationAnimation();
                    }
                }
            });
        } else {
            if (bean.getStatus() == Constants.LOGIN_CODE) {
                UtilsData.getPreference(this, "login").remove("head_url");
                UtilsData.getPreference(this, "login").remove("nickname");
                UtilsData.getPreference(this, "login").remove("is_store");
                UtilsData.getPreference(this, "login").remove("token");
                APP_TOKEN = "";
                Intent intent = new Intent(this, OneLoginMainActivity.class);
                startActivity(intent);
                return;
            }
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 关注和取消关注
     * */
    @Override
    public void onLiveRoomFocusSuccess(VideoRoomGoodListBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (bean.getData().getIs_follow().equals("0")){//未关注
                tv_focus.setText("关注");
                setDrawableResource(getResources().getDrawable(R.drawable.ic_livefocus));
                isFocus = 0;
                if (follow_num>0){
                    follow_num = follow_num-1;
                    tv_fensnum.setText("粉丝: "+Utils.toNumber(follow_num));
                }else {
                    tv_fensnum.setText("粉丝: 0");
                }

            }else {
                isFocus = 1;
                tv_focus.setText("已关注");
                setDrawableResource(null);
                //发送关注消息
                mLiveRoom.sendRoomCustomMsg(String.valueOf(TCConstants.IMCMD_FOCUS), "", (LiveRoom.SendCustomMessageCallback) null);
                follow_num = follow_num+1;
                tv_fensnum.setText("粉丝: "+Utils.toNumber(follow_num));

            }
        } else {
            if (bean.getStatus() == Constants.LOGIN_CODE) {
                UtilsData.getPreference(this, "login").remove("head_url");
                UtilsData.getPreference(this, "login").remove("nickname");
                UtilsData.getPreference(this, "login").remove("is_store");
                UtilsData.getPreference(this, "login").remove("token");
                APP_TOKEN = "";
                Intent intent = new Intent(this, OneLoginMainActivity.class);
                startActivity(intent);
                return;
            }
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onLiveRoomZanSuccess(VideoRoomGoodListBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            zan_num = zan_num+1;
            tv_zancount.setText(Utils.toNumber(zan_num));
            //向ChatRoom发送点赞消息
            mLiveRoom.sendRoomCustomMsg(String.valueOf(TCConstants.IMCMD_PRAISE), "赞", (LiveRoom.SendCustomMessageCallback) null);
        }else {

        }
    }

    @Override
    public void onAddCarSuccess(ConfirmGoodBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            Toast.makeText(this, "加入购物车成功", Toast.LENGTH_SHORT).show();
            if (shop_type == 0) {
                tvCarNum.setText(bean.getData().getCount().getLscount() + "");
                UtilsData.getPreference(this, "carCount").put("car_ls_count", bean.getData().getCount().getLscount());
            } else {
                tvCarNum.setText(bean.getData().getCount().getPfcount() + "");
                UtilsData.getPreference(this, "carCount").put("car_pf_count", bean.getData().getCount().getPfcount());
            }
        } else {
            if (bean.getStatus() == Constants.LOGIN_CODE) {
                UtilsData.getPreference(this, "login").remove("head_url");
                UtilsData.getPreference(this, "login").remove("nickname");
                UtilsData.getPreference(this, "login").remove("is_store");
                UtilsData.getPreference(this, "login").remove("token");
                APP_TOKEN = "";
                Intent intent = new Intent(this, OneLoginMainActivity.class);
                startActivity(intent);
                return;
            }
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }


    /*
     * 方法名：startTranslationAnimation()
     * 功    能：开启平移动画
     * 参    数：无
     * 返回值：无
     */
    private void startTranslationAnimation() {
//        TranslateAnimation startTranslateAnim = new TranslateAnimation(0, 0, -height, 0);
//        startTranslateAnim.setDuration(300);
//        llCar.startAnimation(startTranslateAnim);
        //设置动画，从自身位置的最下端向上滑动了自身的高度，持续时间为500ms
        final TranslateAnimation ctrlAnimation = new TranslateAnimation(
                TranslateAnimation.RELATIVE_TO_SELF, 0, TranslateAnimation.RELATIVE_TO_SELF, 0,
                TranslateAnimation.RELATIVE_TO_SELF, 1, TranslateAnimation.RELATIVE_TO_SELF, 0);
        ctrlAnimation.setDuration(300);     //设置动画的过渡时间
        rlPopupRoot.postDelayed(new Runnable() {
            @Override
            public void run() {
                viewGoodCarBg.setVisibility(View.VISIBLE);
                rlPopupRoot.setVisibility(View.VISIBLE);
                rlPopupRoot.startAnimation(ctrlAnimation);
            }
        }, 300);

    }

    /*
     * 方法名：endTranslationAnimation()
     * 功    能：关闭平移动画
     * 参    数：无
     * 返回值：无
     */
    private void endTranslationAnimation() {
//        TranslateAnimation endTranslateAnim= new TranslateAnimation(0, 0, 0, -height);
//        endTranslateAnim.setDuration(300);
//        llCar.startAnimation(endTranslateAnim);

//        设置动画，从自身位置的最下端向上滑动了自身的高度，持续时间为500ms
        final TranslateAnimation ctrlAnimation = new TranslateAnimation(
                TranslateAnimation.RELATIVE_TO_SELF, 0, TranslateAnimation.RELATIVE_TO_SELF, 0,
                TranslateAnimation.RELATIVE_TO_SELF, 0, TranslateAnimation.RELATIVE_TO_SELF, 1);
        ctrlAnimation.setDuration(300);     //设置动画的过渡时间
        rlPopupRoot.postDelayed(new Runnable() {
            @Override
            public void run() {
                viewGoodCarBg.setVisibility(View.GONE);
                rlPopupRoot.setVisibility(View.GONE);
                rlPopupRoot.startAnimation(ctrlAnimation);
            }
        }, 300);

    }

    /*
     * 方法名：initOnPreDrawListener()
     * 功    能：初始化viewTreeObserver事件监听,重写OnPreDrawListener获取组件高度
     * 参    数：无
     * 返回值：无
     */
    private void initOnPreDrawListener() {
        final ViewTreeObserver viewTreeObserver = this.getWindow().getDecorView().getViewTreeObserver();
        viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                int endPosition[] = new int[2];
                tvCarNum.getLocationInWindow(endPosition);
                // 移除OnPreDrawListener事件监听
                videoGoodListAdapter.setPosition(endPosition, liveId);
                getWindow().getDecorView().getViewTreeObserver().removeOnPreDrawListener(this);

                return true;
            }
        });
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    Intent intent;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_shop_info:

                if (!shopID.isEmpty()) {
                    if (shop_type==0){
                        Intent intent = new Intent(this, ShopActivity.class);
                        intent.putExtra("shop_id", shopID + "");
                        startActivity(intent);
                    }else {
                        intent = new Intent(this, XFDShopDetailsActivity.class);
                        intent.putExtra("shop_id", shopID + "");
                        startActivity(intent);
                    }
                }
                break;
            case R.id.btn_message_input:
                if (EmptyUtil.isEmpty(APP_TOKEN)) {//没有登录去跳转登录
                    intent = new Intent(VideoActivity.this, OneLoginMainActivity.class);
                    startActivity(intent);
                } else {
                    ll_input.setVisibility(View.VISIBLE);
//                    et_input_message.setFocusable(true);
//                    et_input_message.setFocusableInTouchMode(true);
//                    et_input_message.setClickable(true);

                    KeybordUtil.showSoftInput(this,et_input_message);
                 //   showInputMsgDialog();
                }
                break;
            case R.id.confrim_btn://发送
                String msg = et_input_message.getText().toString().trim();
                if (!TextUtils.isEmpty(msg)) {

                    inputMethodManager.showSoftInput(et_input_message, InputMethodManager.SHOW_FORCED);
                    inputMethodManager.hideSoftInputFromWindow(et_input_message.getWindowToken(), 0);
                    et_input_message.setText("");
                    ll_input.setVisibility(View.GONE);
                    mLastDiff = 0;
                    onTextSend(msg,false);
                } else {
                    Toast.makeText(this, "输入内容不能为空!", Toast.LENGTH_LONG).show();
                }
                et_input_message.setText(null);
                break;
            case R.id.img_close://关闭
                stopPlay(true);
                EventBus.getDefault().post(new VideoListMessage(0));
                EventBus.getDefault().post(new VideoListMessage(1));
                mLiveRoom.sendRoomCustomMsg(String.valueOf(TCConstants.IMCMD_EXIT_LIVE), "", (LiveRoom.SendCustomMessageCallback) null);
                finish();
                break;
            case R.id.tv_focus://关注

                if (Utils.isClickQuckily()){
                    return;
                }
                if (isFocus == 1){//取消关注操作
                    dialog.show();
                }else {
                    mPresenter.getLiveRoomFocus(liveId + "");
                }

                break;
            case R.id.btn_goods://商品袋查看上架商品
                //请求直播间的商品列表
                mPresenter.videoRoomGoodList(liveId + "");

                break;
            case R.id.btn_share://分享

                break;
            case R.id.btn_zan://点赞
                if (mHeartLayout != null) {
                    mHeartLayout.addFavor();
                }

                //点赞发送请求限制
                if (mLikeFrequeControl == null) {
                    mLikeFrequeControl = new TCFrequeControl();
                    mLikeFrequeControl.init(2, 1);
                }
                if (mLikeFrequeControl.canTrigger()) {
                    mHeartCount++;
                    mPresenter.getLiveRoomZan(liveId);
                    if (null != mLiveRoom) {
                        mLiveRoom.incCustomInfo("praise", 1);

                    }

                }
                break;
            case R.id.tv_finish://结束返回
                finish();
                break;
            case R.id.tv_lookmore://头像列表
            case R.id.ll_addheadlist://头像列表
                showLiveOnLiveCountDialog();
                break;


        }
    }

    /**
     * 头像列表弹窗
     */
    ShowLiveOnLiveCountDialog showLiveOnLiveCountDialog;

    public void showLiveOnLiveCountDialog() {

        if (showLiveOnLiveCountDialog == null) {
            showLiveOnLiveCountDialog = new ShowLiveOnLiveCountDialog(this,videoMoreAvatarList);
        }
        showLiveOnLiveCountDialog.show();

    }

    private Dialog dialog;
    private void initDialog() {
        dialog = Utils.addDialog(this, R.layout.dialog, R.string.want_to_canclefocus, R.string.confirm, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                mPresenter.getLiveRoomFocus(liveId+"");
            }
        });
    }

    /**
     * 加入IM聊天室
     */
    protected void enterIMRoom() {
        // mGroupId = UtilsData.getPreference(VideoActivity.this,"IMlogin").getString("chat_id");
        mLiveRoom.setLiveRoomListener(this);
        // mGroupId = "@TGS#3NVP655FZ";
        Log.e("TCUserMgr", "进入" + mGroupId);
        mLiveRoom.setmSelfRoleType(2);//游客0，主播1，观众2
        mLiveRoom.enterRoom(mGroupId, mPlayerView, new LiveRoom.EnterRoomCallback() {
            @Override
            public void onError(int errCode, String errInfo) {
                myHandlerReconnection = new MyHandler(VideoActivity.this);//失败重连
                joinCount++;
                if (joinCount < 3) {
                    myHandlerReconnection.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            /**
                             *要执行的操作
                             */
                            enterIMRoom();
                        }
                    }, 500);//0.5秒后执行Runnable中的run方法

                }
                //  showErrorAndQuit(TCConstants.ERROR_MSG_JOIN_GROUP_FAILED + errCode);
                Log.e("TCUserMgr", "进入LiveRoom失败");
                //ToastUtils.s(VideoActivity.this, "加入聊天室失败");
                TCUserMgr.getInstance().uploadLogs(TCConstants.ELK_ACTION_LIVE_PLAY, TCUserMgr.getInstance().getUserId(), -10001, "进入LiveRoom失败", null);
            }

            @Override
            public void onSuccess() {
                mLiveRoom.getAudienceList(mGroupId, new LiveRoom.GetAudienceListCallback() {
                    @Override
                    public void onError(int errCode, String errInfo) {
                        Log.e("mPusherList",mPusherList.size()+"onError"+errCode+"-----"+errInfo);
                    }

                    @Override
                    public void onSuccess(ArrayList<RoomInfo.Audience> audienceList) {
                        Log.e("mPusherList","成员列表onSuccess"+audienceList.size());
                    }
                });
                Log.e("mPusherList",mPusherList.size()+"成员列表");
                // mBgImageView.setVisibility(View.GONE);
                //ToastUtils.s(VideoActivity.this, "加入聊天室成功");
                mLiveRoom.sendRoomCustomMsg(String.valueOf(TCConstants.IMCMD_ENTER_LIVE), "", (LiveRoom.SendCustomMessageCallback) null);
                TCUserMgr.getInstance().uploadLogs(TCConstants.ELK_ACTION_LIVE_PLAY, TCUserMgr.getInstance().getUserId(), 10000, "进入LiveRoom成功", null);
                // mvpPresenter.getJoinLive(SharedPreferencesManager.getSsotoken(),playerId);

                if (isFirst){
                    TCChatEntity entity = new TCChatEntity();
                    entity.setSenderName("平台提醒:");
                    entity.setContext("请您在拍下时确认购买商品 和主播实际描述一致，禁止线下交易， 谨防上当受骗！");
                    entity.setType(TCConstants.TEXT_TYPE);

                    notifyMsg(entity);
                    isFirst = false;
                }


            }
        });

        Log.e("startPlay", "startPlay");
    }

    /**
     * 停止播放
     */
    protected void stopPlay(boolean clearLastFrame) {
        if (mPlaying && mLiveRoom != null) {
            Log.e("stopPlay", "stopPlay");
            mLiveRoom.sendRoomCustomMsg(String.valueOf(TCConstants.IMCMD_EXIT_LIVE), "", (LiveRoom.SendCustomMessageCallback) null);
            mLiveRoom.exitRoom(new LiveRoom.ExitRoomCallback() {
                @Override
                public void onError(int errCode, String errInfo) {
                    TXLog.w(TAG, "exit room error : " + errInfo);
                }

                @Override
                public void onSuccess() {
                    TXLog.d(TAG, "exit room success ");
                }
            });
            stopTickWork();
            mPlaying = false;
            mLiveRoom.setLiveRoomListener(null);
            //5. 结束普通流播放
            if (mLivePlayer != null) {
                Log.e("stopPlay", "stopPlay结束普通流播放");
                mLivePlayer.stopPlay(true);
                mLivePlayer.setPlayerView(null);
            }
        }
    }

    /**
     * 发消息弹出框
     */
    private void showInputMsgDialog() {
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = mInputTextMsgDialog.getWindow().getAttributes();

        lp.width = (display.getWidth()); //设置宽度
        mInputTextMsgDialog.getWindow().setAttributes(lp);
        mInputTextMsgDialog.setCancelable(true);
        mInputTextMsgDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        mInputTextMsgDialog.show();
    }

    @Override
    public void onGetPusherList(List<PusherInfo> pusherList) {
        Log.e("mPusherList",mPusherList.size()+"成员列表");
        for (PusherInfo pusherInfo : pusherList) {
            mPusherList.add(pusherInfo);
            onPusherJoin(pusherInfo);
        }


    }

    @Override
    public void onPusherJoin(PusherInfo pusherInfo) {
        if (pusherInfo == null || pusherInfo.userID == null) {
            return;
        }

        final TCVideoWidget videoView = mPlayerList.applyVideoView(pusherInfo.userID);
        if (videoView == null) {
            return;
        }

        if (mPusherList != null) {
            boolean exist = false;
            for (PusherInfo item : mPusherList) {
                if (pusherInfo.userID.equalsIgnoreCase(item.userID)) {
                    exist = true;
                    break;
                }
            }
            if (exist == false) {
                mPusherList.add(pusherInfo);
            }
        }

        videoView.startLoading();
        mLiveRoom.addRemoteView(videoView.videoView, pusherInfo, new LiveRoom.RemoteViewPlayCallback() {
            @Override
            public void onPlayBegin() {
                videoView.stopLoading(false); //推流成功，stopLoading 小主播隐藏踢人的button
            }

            @Override
            public void onPlayError() {
                videoView.stopLoading(false);
            }
        }); //开启远端视频渲染
    }

    @Override
    public void onPusherQuit(PusherInfo pusherInfo) {
        if (mPusherList != null) {
            Iterator<PusherInfo> it = mPusherList.iterator();
            while (it.hasNext()) {
                PusherInfo item = it.next();
                if (pusherInfo.userID.equalsIgnoreCase(item.userID)) {
                    it.remove();
                    break;
                }
            }
        }

        mLiveRoom.deleteRemoteView(pusherInfo);//关闭远端视频渲染
        mPlayerList.recycleVideoView(pusherInfo.userID);
    }

    @Override
    public void onRecvJoinPusherRequest(String userID, String userName, String userAvatar) {

    }

    @Override
    public void onKickOut() {
        Toast.makeText(getApplicationContext(), "不好意思，您被主播踢开", Toast.LENGTH_LONG).show();
        //stopLinkMic();
    }

    @Override
    public void onRecvPKRequest(String userID, String userName, String userAvatar, String streamUrl) {

    }

    @Override
    public void onRecvPKFinishRequest(String userID) {

    }

    @Override
    public void onRecvRoomTextMsg(String roomID, String userID, String userName, String userAvatar, String message) {
        Log.e("onGroupTextMessage", "onRecvRoomTextMsg群消息==" + message);
        TCSimpleUserInfo userInfo = new TCSimpleUserInfo(userID, userName, userAvatar);
        handleTextMsg(userInfo, message);
    }

    @Override
    public void onRecvRoomCustomMsg(String roomID, String userID, String userName, String userAvatar, String cmd, String message) {
        Log.e("onGroupTextMessage", "onRecvRoomCustomMsg群消息==" + message);
        //  mvpPresenter.getLiveRenQi(SharedPreferencesManager.getSsotoken(),playerId);
        TCSimpleUserInfo userInfo = new TCSimpleUserInfo(userID, userName, userAvatar);
        int type = Integer.valueOf(cmd);
        switch (type) {
            case TCConstants.IMCMD_ENTER_LIVE:
                handleMemberJoinMsg(userInfo);
                break;
            case TCConstants.IMCMD_EXIT_LIVE:
                handleMemberQuitMsg(userInfo);
                break;
            case TCConstants.IMCMD_PRAISE:
                handlePraiseMsg(userInfo);
                break;
            case TCConstants.IMCMD_PAILN_TEXT:
                handleTextMsg(userInfo, message);
                break;
            case TCConstants.IMCMD_DANMU:
                handleDanmuMsg(userInfo, message);
                break;
            case TCConstants.IMCMD_PUSTER_EXIT://自定义直播结束消息
                handlePusterQuitMsg(userInfo);
                break;
            case TCConstants.IMCMD_FOCUS://自定义关注直播消息
                handlePusterFocusMsg(userInfo);
                break;
            case TCConstants.IMCMD_ADDCART://自定义商品加入到购物车消息
                handleAddCartMsg(userInfo,message);
                break;
            default:
                break;
        }
    }

    @Override
    public void onRoomClosed(String roomID) {
        //stopLinkMic();
        rl_end_video.setVisibility(View.VISIBLE);
        EventBus.getDefault().post(new VideoListMessage(0));
        //showErrorAndQuit(TCConstants.ERROR_MSG_LIVE_STOPPED);
    }

    @Override
    public void onDebugLog(String log) {
        Log.e("onDebugLog",log+"----------");
        TXLog.d(TAG, log);
    }

    @Override
    public void onError(int errorCode, String errorMessage) {
        Log.e("onError","onError----");
        showErrorAndQuit(TCConstants.ERROR_RTMP_PLAY_FAILED);
    }

    @Override
    public void onLivePlayEvent(int event, Bundle params) {
        Log.e("onError","onLivePlayEvent--");
        report(event);
    }

    /**
     * 小直播ELK上报内容
     *
     * @param event
     */
    private void report(int event) {
        switch (event) {
            case TXLiveConstants.PLAY_EVT_RCV_FIRST_I_FRAME:
                Log.e("TCUserMgr", "视频播放成功");
                //    TCUserMgr.getInstance().uploadLogs(TCConstants.ELK_ACTION_LIVE_PLAY, TCUserMgr.getInstance().getUserId(), 0, "视频播放成功", null);
                break;
            case TXLiveConstants.PLAY_ERR_NET_DISCONNECT:
                Log.e("TCUserMgr", "网络断连,且经多次重连抢救无效,可以放弃治疗,更多重试请自行重启播放");
                // TCUserMgr.getInstance().uploadLogs(TCConstants.ELK_ACTION_LIVE_PLAY, TCUserMgr.getInstance().getUserId(), -1, "网络断连,且经多次重连抢救无效,可以放弃治疗,更多重试请自行重启播放", null);
                break;
            case TXLiveConstants.PLAY_ERR_GET_RTMP_ACC_URL_FAIL:
                Log.e("TCUserMgr", "获取加速拉流地址失败");
                // TCUserMgr.getInstance().uploadLogs(TCConstants.ELK_ACTION_LIVE_PLAY, TCUserMgr.getInstance().getUserId(), -2, "获取加速拉流地址失败", null);
                break;
            case TXLiveConstants.PLAY_ERR_FILE_NOT_FOUND:
                Log.e("TCUserMgr", "播放文件不存在");
                // TCUserMgr.getInstance().uploadLogs(TCConstants.ELK_ACTION_LIVE_PLAY, TCUserMgr.getInstance().getUserId(), -3, "播放文件不存在", null);
                break;
            case TXLiveConstants.PLAY_ERR_HEVC_DECODE_FAIL:
                Log.e("TCUserMgr", "H265解码失败");
                // TCUserMgr.getInstance().uploadLogs(TCConstants.ELK_ACTION_LIVE_PLAY, TCUserMgr.getInstance().getUserId(), -4, "H265解码失败", null);
                break;
            case TXLiveConstants.PLAY_ERR_HLS_KEY:
                Log.e("TCUserMgr", "HLS解码Key获取失败");
                //TCUserMgr.getInstance().uploadLogs(TCConstants.ELK_ACTION_LIVE_PLAY, TCUserMgr.getInstance().getUserId(), -5, "HLS解码Key获取失败", null);
                break;
            case TXLiveConstants.PLAY_ERR_GET_PLAYINFO_FAIL:
                Log.e("TCUserMgr", "获取点播文件信息失败");
                //TCUserMgr.getInstance().uploadLogs(TCConstants.ELK_ACTION_LIVE_PLAY, TCUserMgr.getInstance().getUserId(), -6, "获取点播文件信息失败", null);
                break;

        }
    }

    protected void showErrorAndQuit(String errorMsg) {
        stopPlay(true);

        Intent rstData = new Intent();
        rstData.putExtra(TCConstants.ACTIVITY_RESULT, errorMsg);
        //TODO:返回直播列表页面刷新页面
        //  setResult(TCLiveListFragment.START_LIVE_PLAY,rstData);

        if (!mErrDlgFragment.isAdded() && !this.isFinishing()) {
            Bundle args = new Bundle();
            args.putString("errorMsg", errorMsg);
            mErrDlgFragment.setArguments(args);
            mErrDlgFragment.setCancelable(false);

            //此处不使用用.show(...)的方式加载dialogfragment，避免IllegalStateException
            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            transaction.add(mErrDlgFragment, "loading");
            transaction.commitAllowingStateLoss();
        }
    }

    @Override
    public void onBackPressed() {
        if (viewGoodCarBg.getVisibility() == View.VISIBLE) {
            endTranslationAnimation();
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        // mLivePlayer.stopPlay(true); // true 代表清除最后一帧画面
        mPlayerView.onDestroy();
        mPresenter.detachView();
        if (mDanmuMgr != null) {
            mDanmuMgr.destroy();
            mDanmuMgr = null;
        }

        stopPlay(true);

        mPlayerList.recycleVideoView();
        mPlayerList = null;
        // stopLinkMic();
        mHandler.removeCallbacksAndMessages(null);
        mHandler = null;
        if (null!=myHandlerReconnection){
            myHandlerReconnection.removeCallbacksAndMessages(null);
            myHandlerReconnection = null;
        }
        hideNoticeToast();


        long endPushPts = System.currentTimeMillis();
        long diff = (endPushPts - mStartPushPts) / 1000;
        //  TCUserMgr.getInstance().uploadLogs(TCConstants.ELK_ACTION_LIVE_PLAY_DURATION, TCUserMgr.getInstance().getUserId(), diff, "直播播放时长", null);
    }

    private void notifyMsg(final TCChatEntity entity) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
//                if(entity.getType() == TCConstants.PRAISE) {
//                    if(mArrayListChatEntity.contains(entity))
//                        return;
//                }
                if (mArrayListChatEntity.size() > 1000) {
                    while (mArrayListChatEntity.size() > 900) {
                        mArrayListChatEntity.remove(0);
                    }
                }

                mArrayListChatEntity.add(entity);
                mChatMsgListAdapter.notifyDataSetChanged();
            }
        });
    }

    public void handleMemberJoinMsg(TCSimpleUserInfo userInfo) {
        //更新头像列表 返回false表明已存在相同用户，将不会更新数据
//        if (!mAvatarListAdapter.addItem(userInfo))
//            return;

        mCurrentMemberCount++;
        mTotalMemberCount++;
        //   mMemberCount.setText(String.format(Locale.CHINA,"%d",mCurrentMemberCount));

        //左下角显示用户加入消息
        TCChatEntity entity = new TCChatEntity();
        entity.setSenderName("通知");
        if (TextUtils.isEmpty(userInfo.nickname)){
            msgContext = userInfo.userid;
            entity.setContext(userInfo.userid + "加入直播");
        } else{
            msgContext = userInfo.nickname;
            entity.setContext(userInfo.nickname + "加入直播");
        }
        //添加到消息集合中弹窗处理消息
        addMsgList(TCConstants.IMCMD_ENTER_LIVE, msgContext);

        notifyTopHeadList(userInfo,"add");
//        entity.setType(TCConstants.IMCMD_ENTER_LIVE);
//        notifyMsg(entity);
        //showSelTimePop();
    }

    /**
     * 更新头部头像列表
     * */
    private void notifyTopHeadList(TCSimpleUserInfo userInfo,String type) {
        boolean isAddedTop = false;
        boolean isAdded = false;
        int topIndex = 0;
        int bottomIndex = 0;
        for (int i = 0; i < videoTopAvatarList.size(); i++) {
            if (videoTopAvatarList.get(i).getUserId().equals(userInfo.userid)){
                isAddedTop = true;
                topIndex = i;
                break;
            }
        }

        for (int i = 0; i < videoMoreAvatarList.size(); i++) {
            if (videoTopAvatarList.get(i).getUserId().equals(userInfo.userid)){
                isAdded = true;
                bottomIndex = i;
                break;
            }
        }

        if (!isAdded){
            if (type.equals("add")){
                videoMoreAvatarList.add(0,new VideoAvatarListBeen(userInfo.headpic,userInfo.nickname,userInfo.userid));
            }
        }else {
            if (!type.equals("add")){
                videoMoreAvatarList.remove(bottomIndex);
            }
        }

        if (!isAddedTop){
            if (type.equals("add")){
                videoTopAvatarList.add(0,new VideoAvatarListBeen(userInfo.headpic,userInfo.nickname,userInfo.userid));
            }

        }else {
        if (!type.equals("add")){
            videoTopAvatarList.remove(bottomIndex);
        }
    }

        if (videoTopAvatarList.size()>4){
            videoTopAvatarList.remove(videoTopAvatarList.size()-1);
        }
        if (videoMoreAvatarList.size()>200){
            videoMoreAvatarList.remove(videoTopAvatarList.size()-1);
        }

        addTopHeadView();//动态添加刷新
        //videoTopHeadListAdapter.refreshDatas(videoTopAvatarList);
    }

    /**
     * zf自定义商品被加入到购物车方法
     * */
    public void handleAddCartMsg(TCSimpleUserInfo userInfo,String message) {
        //添加到消息集合中弹窗处理消息
        addMsgList(TCConstants.IMCMD_ADDCART, userInfo.nickname+"将"+message);

    }
    /**
     * zf自定义关注房间方法
     * */
    public void handlePusterFocusMsg(TCSimpleUserInfo userInfo) {

//        TCChatEntity entity = new TCChatEntity();
//        entity.setSenderName("通知");
//        if (TextUtils.isEmpty(userInfo.nickname)){
//            entity.setContext(userInfo.userid + "关注了直播间");
//        }else {
//            entity.setContext(userInfo.nickname + "关注了直播间");
//        }
//
//        entity.setType(TCConstants.MEMBER_ENTER);
//        notifyMsg(entity);
        //添加到消息集合中弹窗处理消息
        addMsgList(TCConstants.IMCMD_FOCUS, msgContext);

    }

    /**
     * zf自定义直播结束方法
     */
    public void handlePusterQuitMsg(TCSimpleUserInfo userInfo) {
        if (mCurrentMemberCount > 0)
            mCurrentMemberCount--;
        else
            Log.d(TAG, "接受多次退出请求，目前人数为负数");

        //   mMemberCount.setText(String.format(Locale.CHINA,"%d",mCurrentMemberCount));

        //   mAvatarListAdapter.removeItem(userInfo.userid);

//        TCChatEntity entity = new TCChatEntity();
//        entity.setSenderName("通知");
//        if (TextUtils.isEmpty(userInfo.nickname))
//            entity.setContext(userInfo.userid + "退出直播");
//        else
//            entity.setContext(userInfo.nickname + "退出直播");
//        entity.setType(TCConstants.MEMBER_EXIT);
//        notifyMsg(entity);

        //showErrorAndQuit("直播结束");
        stopPlay(true);
        if (EmptyUtil.isNotEmpty(showLiveOnLiveCountDialog)){
            showLiveOnLiveCountDialog.dismiss();
        }
        rl_end_video.setVisibility(View.VISIBLE);//展示结束布局
        EventBus.getDefault().post(new VideoListMessage(0));
    }

    public void handleMemberQuitMsg(TCSimpleUserInfo userInfo) {
        if (mCurrentMemberCount > 0)
            mCurrentMemberCount--;
        else
            Log.d(TAG, "接受多次退出请求，目前人数为负数");

        notifyTopHeadList(userInfo,"move");

        //   mMemberCount.setText(String.format(Locale.CHINA,"%d",mCurrentMemberCount));

        //   mAvatarListAdapter.removeItem(userInfo.userid);

//        TCChatEntity entity = new TCChatEntity();
//        entity.setSenderName("通知");
//        if (TextUtils.isEmpty(userInfo.nickname))
//            entity.setContext(userInfo.userid + "退出直播");
//        else
//            entity.setContext(userInfo.nickname + "退出直播");
//        entity.setType(TCConstants.MEMBER_EXIT);
//        notifyMsg(entity);
    }

    public void handlePraiseMsg(TCSimpleUserInfo userInfo) {
//        TCChatEntity entity = new TCChatEntity();
//
//        entity.setSenderName("通知");
//        if (TextUtils.isEmpty(userInfo.nickname))
//            entity.setContext(userInfo.userid + "点了个赞");
//        else
//            entity.setContext(userInfo.nickname + "点了个赞");
        if (mHeartLayout != null) {
            mHeartLayout.addFavor();
        }
        mHeartCount++;
        zan_num = zan_num+1;
        tv_zancount.setText(Utils.toNumber(zan_num));
//        entity.setType(TCConstants.MEMBER_ENTER);
//        notifyMsg(entity);

    }

    public void handleDanmuMsg(TCSimpleUserInfo userInfo, String text) {
        handleTextMsg(userInfo, text);
        if (mDanmuMgr != null) {
            mDanmuMgr.addDanmu(userInfo.headpic, userInfo.nickname, text);
        }
    }

    public void handleTextMsg(TCSimpleUserInfo userInfo, String text) {
        TCChatEntity entity = new TCChatEntity();
        entity.setSenderName(userInfo.nickname);
        entity.setContext(text);
        entity.setType(TCConstants.TEXT_TYPE);

        notifyMsg(entity);
    }

    /**
     * TextInputDialog发送回调
     *
     * @param msg       文本信息
     * @param danmuOpen 是否打开弹幕
     */
    public void onTextSend(String msg, boolean danmuOpen) {
        if (msg.length() == 0)
            return;
        try {
            byte[] byte_num = msg.getBytes("utf8");
            if (byte_num.length > 160) {
                Toast.makeText(this, "请输入内容", Toast.LENGTH_SHORT).show();
                return;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return;
        }

        //消息回显
        TCChatEntity entity = new TCChatEntity();
        if (EmptyUtil.isNotEmpty(UtilsData.getPreference(VideoActivity.this,"login").getString("nickname"))){
            entity.setSenderName(UtilsData.getPreference(VideoActivity.this,"login").getString("nickname"));
        }else {
            entity.setSenderName("我:");
        }
        entity.setContext(msg);
        entity.setType(TCConstants.TEXT_TYPE);
        notifyMsg(entity);

        if (danmuOpen) {
            if (mDanmuMgr != null) {
                mDanmuMgr.addDanmu(mHeadPic, mNickname, msg);
            }
            mLiveRoom.sendRoomCustomMsg(String.valueOf(TCConstants.IMCMD_DANMU), msg, new LiveRoom.SendCustomMessageCallback() {
                @Override
                public void onError(int errCode, String errInfo) {
//                    Log.w(TAG, "sendRoomDanmuMsg error: " + errInfo);
                }

                @Override
                public void onSuccess() {
                    Log.d(TAG, "sendRoomDanmuMsg success");
                }
            });
        } else {
            mLiveRoom.sendRoomTextMsg(msg, new LiveRoom.SendTextMessageCallback() {
                @Override
                public void onError(int errCode, String errInfo) {
                    Log.d(TAG, "sendRoomTextMsg error:" + errCode + errInfo);
                }

                @Override
                public void onSuccess() {
                    Log.d(TAG, "sendRoomTextMsg success:");
                }
            });
        }
    }

    private Toast mNoticeToast;
    private Timer mNoticeTimer;

    private void showNoticeToast(String text) {
        if (mNoticeToast == null) {
            mNoticeToast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG);
        }

        if (mNoticeTimer == null) {
            mNoticeTimer = new Timer();
        }

        mNoticeToast.setText(text);
        mNoticeTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                mNoticeToast.show();
            }
        }, 0, 3000);

    }

    private void hideNoticeToast() {
        if (mNoticeToast != null) {
            mNoticeToast.cancel();
            mNoticeToast = null;
        }
        if (mNoticeTimer != null) {
            mNoticeTimer.cancel();
            mNoticeTimer = null;
        }
    }

    /**
//     * 关注，进入房间，加入购物车，购买消息飘窗
//     * */
//    private CustomerPopwindow customerPopwindow;
//    /**
//     * 选择时间弹窗
//     * **/
//    public void showSelTimePop() {
//
//        customerPopwindow = new CustomerPopwindow(VideoActivity.this);
//        customerPopwindow.showPopupWindow(msgType,msgContext);
//        customerPopwindow.setOutsideTouchable(false);
//        customerPopwindow.setFocusable(false);
//        customerPopwindow.setTouchable(true);
//    }

    private SendValidateTimerUtil mTimer = new SendValidateTimerUtil();
    private int mDisableTimeTemp = 0;
    private int countDown;//活动倒计时秒数
    /**开启倒计时*/
    public void startTickWork() {

        mTimer.startWork(0, 1000, new SendValidateTimerUtil.SDTimerListener() {
            @Override
            public void onWorkMain() {
                tickWork();
            }

            @Override
            public void onWork() {
            }
        });
        // }
    }

    /**
     * 每秒钟调用一次
     */
    private void tickWork() {
        mDisableTimeTemp++;
        //执行弹窗效果
        if (mDisableTimeTemp%3==0){
            if (msgBeenList.size()>0){
                showPopAnimation();
            }
        }

    }

    public void stopTickWork() {
        mTimer.stopWork();
        mDisableTimeTemp = countDown;

    }
    /**
     * 收到消息后维护一个消息集合
     * */
    private void addMsgList(int msgType,String msgContext){
        msgBeenList.add(new CustomerMsgBeen(msgType,msgContext));
    }

    /**
     * 初始化动画监听
     * */
    public void initAnimationListener(){
        transtoLeftAnim = AnimationUtils.loadAnimation(VideoActivity.this,R.anim.pop_in);
        transtoRightAnim = AnimationUtils.loadAnimation(VideoActivity.this,R.anim.pop_out);
        transtoLeftAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {

                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        /**
                         *要执行的操作
                         */
                        tv_pop.startAnimation(transtoRightAnim);
                    }
                }, 1000);//1秒后执行Runnable中的run方法
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        transtoRightAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                tv_pop.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private void showPopAnimation() {
        tv_pop.setVisibility(View.VISIBLE);
        if (msgBeenList.get(0).getMsgType() == TCConstants.IMCMD_ENTER_LIVE){//加入直播间通知
            tv_pop.setText(msgBeenList.get(0).getMsgContext()+"来了~");
            tv_pop.setBackgroundResource(R.drawable.shape_fe2451conner3);
        }else if (msgBeenList.get(0).getMsgType() == TCConstants.IMCMD_FOCUS){//关注直播间通知
            tv_pop.setText(msgBeenList.get(0).getMsgContext()+"关注了主播");
            tv_pop.setBackgroundResource(R.drawable.shape_db21fdconner3);
        }else if (msgBeenList.get(0).getMsgType() == TCConstants.IMCMD_ADDCART){//关注商品加入到购物车通知
            tv_pop.setText(msgBeenList.get(0).getMsgContext()+"号商品加入了购物车");
            tv_pop.setBackgroundResource(R.drawable.shape_fdcc21conner3);
        }else if (msgBeenList.get(0).getMsgType() == TCConstants.IMCMD_BUY){//收到已购买商品通知
            tv_pop.setText(msgBeenList.get(0).getMsgContext()+"");
            tv_pop.setBackgroundResource(R.drawable.shape_fdcc21conner3);
        }
        tv_pop.startAnimation(transtoLeftAnim);
        msgBeenList.remove(0);
    }


    private static class MyHandler extends Handler {
        private final WeakReference<VideoActivity> mActivity;

        public MyHandler(VideoActivity activity) {
            mActivity = new WeakReference<VideoActivity>(activity);

        }

        @Override
        public void handleMessage(Message msg) {
            VideoActivity activity = mActivity.get();
            if (activity != null) {
                //do Something
            }
        }
    }
}
